using System;
using System.IO;
using System.Text;
using WebServer.BusinessLogic.Helpers;

namespace WebServer.BusinessLogic.Web.Cache
{
    public class CacheManager
    {
        private static CacheManagerInstance _instance;

        private static Object _syncRoot = new Object();

        public static CacheManagerInstance Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (_syncRoot)
                    {
                        if (_instance == null)
                        {
                            _instance = new CacheManagerInstance();
                        }
                    }
                }

                return _instance;
            }
        }

        public static byte[] GetCacheOrFile(string cacheKey, string filePath)
        {
            byte[] data;
            bool saveToCache = false;

            if (Configurator.Instance.IsCacheEnabled)
            {
                var cacheItem = Instance.GetCachedItem(cacheKey);
                if (cacheItem != null)
                {
                    data = cacheItem.Data;
                    return data;
                }
                
                saveToCache = true;
            }

            data = Utils.ReadBytesFromFile(filePath);
            if (saveToCache)
            {
                Instance.AddItem(cacheKey, data);
            }
                
            return data;
            
        }

        
    }
}